﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionUtil.DataStructure.Collections
{
    class LinkedCollection : Collection
    {
        private LinkedNode first;
        private int size;

        public LinkedCollection()
        {
            size = 0;
            first = null;
        }

        public void Add(object e)
        {
            first = new LinkedNode(e, first);
            size++;           
        }

        public void Remove(object e)
        {
            LinkedNode p = first;
            while(p != null ){
                if (p.next.element.Equals(e)) break;
                p = p.next;
            }
            if (p != null)
            {
                p.next = p.next.next;
            }
            size--;
        }

        public bool Contain(object e)
        {
            LinkedNode node = first;
            while (node != null)
            {
                if (node.element.Equals(e))
                {
                    return true;
                }
                node = node.next;
            }
            return false;
        }

        public bool IsEmpty()
        {
            return first == null;
        }

        public int Size()
        {
            return size;
        }

        public override string ToString()
        {
            string ret = "[";
            LinkedNode node = first;
            while (node != null)
            {
                ret += node.element+",";
                node = node.next;
            }
            return ret+"]";
        }

        class LinkedNode
        {
            public Object element{get;set;}
            public LinkedNode next{get;set;}

            public LinkedNode(Object element, LinkedNode next)
            {
                this.element = element;
                this.next = next;
            }        
        }
    }
}
